<!-- src/components/HistoryDialog.vue -->
<template>
  <t-dialog
    :visible="localVisible"
    placement="center"
    width="800px"
    :footer="false"
    :on-close="handleClose"
    :close-btn="false"
  >
    <!-- 新增：搜索框和创建按钮 -->
    <!--    <div class="dialog-header">-->
    <!--      <t-input v-model="searchKey" placeholder="搜索会话" clearable class="search-input" @change="handleSearch">-->
    <!--        <template #prefix-icon>-->
    <!--          <t-icon name="search" />-->
    <!--        </template>-->
    <!--      </t-input>-->
    <!--    </div>-->
    <!-- 加载状态 -->
    <t-loading :loading="loading" text="会话加载中...">
      <div class="history-list">
        <!-- 创建新会话 -->
        <div class="session-title">操作</div>
        <div class="session-item" data-type="new-chat" @click="createNewSession">
          <div class="session-header">
            <div class="title-container">
              <t-icon name="edit" />
              <span class="title">创建新聊天</span>
            </div>
          </div>
        </div>
        <!-- 会话列表 -->
        <div class="session-title">会话</div>
        <div
          v-for="session in filteredSessions"
          :key="session.id"
          class="session-item"
          @click="handleSelect(session.id)"
        >
          <div class="session-header">
            <div class="title-container">
              <span class="title">{{ session.name }}</span>
              <t-tag v-if="session.inputs?.scene" theme="primary" variant="light-outline" size="small">
                {{ session.inputs.scene }}
              </t-tag>
            </div>
            <span class="time">{{ formatTime(session.updated_at) }}</span>
          </div>
          <!-- <div class="preview">{{ session.introduction }}</div> -->
        </div>
      </div>
    </t-loading>

    <!-- 空状态 -->
    <template v-if="!loading && sessions.length === 0">
      <div class="empty">
        <t-icon name="file-unknown" size="24px" />
        <p>暂无历史会话</p>
      </div>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { fetchConversations } from '@/api/coze'; // 新增创建接口
import { formatTime } from '@/utils/date';
import { useUserStore } from '@/store';

const router = useRouter();
const user = useUserStore();

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits(['update:visible', 'select', 'new-session']); // 新增事件

// 数据状态
const sessions = ref([]);
const loading = ref(false);
const searchKey = ref('');
const localVisible = ref(props.visible);

// 监听 props.visible 变化，更新本地 visible 状态
watch(
  () => props.visible,
  async (newVal) => {
    localVisible.value = newVal;
    if (newVal) {
      await loadSessions();
    }
  },
);

// 监听本地 visible 的变化，同步通知父组件
watch(localVisible, (val) => {
  emit('update:visible', val);
});

// 加载历史会话
const loadSessions = async () => {
  try {
    loading.value = true;
    const params = {
      user: user.userInfo?.name,
      last_id: '',
      limit: 20,
    };
    const res = await fetchConversations(params);
    sessions.value = res.data;
  } catch (error) {
    console.error('加载失败:', error);
    sessions.value = [];
  } finally {
    loading.value = false;
  }
};

// 选择会话
const handleSelect = async (sessionId: string) => {
  try {
    emit('select', sessionId);
    emit('update:visible', false);
  } catch (error) {
    console.error('获取详情失败:', error);
  }
};

// 计算属性实现搜索
const filteredSessions = computed(() => {
  if (!searchKey.value) return sessions.value;
  const keyword = searchKey.value.toLowerCase();
  return sessions.value.filter(
    (session) => session.name.toLowerCase().includes(keyword) || session.introduction?.toLowerCase().includes(keyword),
  );
});

// 创建会话方法
const createNewSession = () => {
  try {
    emit('new-session'); // 触发新建会话事件
    loadSessions(); // 刷新列表
    emit('update:visible', false);
    router.push('/dashboard/chat');
  } catch (error) {
    console.error('创建失败:', error);
  }
};

const handleSearch = () => {
  console.log('搜索会话列表');
};

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false);
};
</script>

<style lang="less" scoped>
.dialog-header {
  display: flex;
  gap: 12px;
  //padding: 0 16px 16px;
  //border-bottom: 1px solid var(--td-component-stroke);

  .search-input {
    flex: 1;
  }
}

.history-list {
  max-height: 60vh;
  overflow-y: auto;
}
.session-title {
  padding: 12px 8px;
  color: var(--td-text-color-placeholder);
  text-align: left; /* 名称左对齐 */
}
.session-item {
  padding: 12px;
  //border-bottom: 1px solid var(--td-component-stroke);
  border-radius: 15px;
  cursor: pointer;
  transition: background 0.3s;

  &:hover {
    border-radius: 15px;
    background: var(--td-bg-color-container-hover);
  }
  &[data-type='new-chat'] {
    border-radius: 15px;
    background: var(--td-bg-color-container-hover);
    cursor: pointer; /* 默认光标为指针 */
  }
}

.title-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.session-header {
  display: flex;
  justify-content: space-between; /* 名称和时间分列两侧 */
  align-items: center;

  .title {
    text-align: left; /* 名称左对齐 */
    font-weight: 500;
    color: var(--td-text-color-primary);
  }

  .time {
    flex-shrink: 0; /* 防止时间被挤压 */
    color: var(--td-text-color-placeholder);
    font-size: 12px;
  }
}

.preview {
  color: var(--td-text-color-secondary);
  font-size: 12px;
  margin-top: 4px;
  @include text-ellipsis(2);
}

.empty {
  text-align: center;
  padding: 40px 0;
  color: var(--td-text-color-placeholder);
}
</style>
